package controllers;

import models.*;
import org.apache.commons.lang.StringUtils;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import play.mvc.With;
import util.JsonResponse;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: bicho
 * Date: 22/01/12
 * Time: 16:19
 * To change this template use File | Settings | File Templates.
 */

@With(Secure.class)
@Check(Profile.SUPERADMIN)
@CRUD.For(Inscription.class)
public class Inscriptions extends CRUD {

    public static void list(int page, String search, String searchFields, String orderBy, String order) {
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        if (page < 1) {
            page = 1;
        }
        List<Model> objects = type.findPage(page, search, searchFields, orderBy, order, (String) request.args.get("where"));
        Long count = type.count(search, searchFields, (String) request.args.get("where"));
        Long totalCount = type.count(null, null, (String) request.args.get("where"));
        try {
            render(type, objects, count, totalCount, page, orderBy, order);
        } catch (TemplateNotFoundException e) {
            render("CRUD/list.html", type, objects, count, totalCount, page, orderBy, order);
        }
    }

    public static void listForPerson(String personId) {
        Person person = getPersonFromPersonId(personId);

        List<PersonDocument> personDocuments = person.personDocuments;
        List<Inscription> objects = new ArrayList<Inscription>();
        for (PersonDocument personDocument : personDocuments) {
            objects.addAll(personDocument.inscriptions);
        }
        ObjectType type = ObjectType.get(getControllerClass());
        int count = objects.size();
        int totalCount = objects.size();
        int page = 1;
        String orderBy = null;
        String order = null;
        render(type, person, objects, count, totalCount, page, orderBy, order);

    }

    public static void blankForPerson(String personId) throws Exception {

        Person person = getPersonFromPersonId(personId);
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        Constructor<?> constructor = type.entityClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        Model object = (Model) constructor.newInstance();
        try {
            render(type, person, object);
        } catch (TemplateNotFoundException e) {
            render("CRUD/blank.html", type, object);
        }
    }


    public static void show(String id) throws Exception {
        List<DocumentType> documentsTypes = DocumentType.findAll();
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        Model object = type.findById(id);
        notFoundIfNull(object);
        try {
            render(type, object, documentsTypes);
        } catch (TemplateNotFoundException e) {
            render("CRUD/show.html", type, object, documentsTypes);
        }
    }

    public static void save(String id) throws Exception {
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        Model object = type.findById(id);
        notFoundIfNull(object);
        Inscription inscription = (Inscription) object;
        String profileId = params.getRootParamNode().getChild("object.profile.id").getValues()[0];
        if (!inscription.profile.id.toString().equals(profileId)) {
            inscription.profile = Profile.findById(Long.valueOf(profileId).longValue());
        }
//        String person_name = params.get("person_name");
//        String person_surname = params.get("person_surname");

//        if(!inscription.personDocument.person.name.equals(person_name) |
//        !inscription.personDocument.person.surname.equals(person_surname)  ){
//            Person person = inscription.personDocument.person;
//            person.name = person_name;
//            person.surname = person_surname;
//            person.save();
//        }


//        int i = 0;
//        Binder.bindBean(params.getRootParamNode(), "object", object);
//        validation.valid(object);
//        if (validation.hasErrors()) {
//            renderArgs.put("error", play.i18n.Messages.get("crud.hasErrors"));
//            try {
//                render(request.controller.replace(".", "/") + "/show.html", type, object);
//            } catch (TemplateNotFoundException e) {
//                render("CRUD/show.html", type, object);
//            }
//        }
//        object._save();
        inscription.save();
        flash.success(play.i18n.Messages.get("crud.saved", type.modelName));
        if (params.get("_save") != null) {
            redirect(request.controller + ".list");
        }
        redirect(request.controller + ".show", object._key());
    }

    public static void changeIncriptionStatus(String id, boolean checked) {
        //TODO verifyTokerForm
        Inscription inscription = Inscription.findById(Long.valueOf(id).longValue());
        inscription.isActive = checked;
        //TODO Revisar el mensaje que deberia emitir, como 'isActive para ...'
        inscription.save();
        boolean f = true;
        String message = "Se actualizó a " + inscription.personDocument.person.name;
        renderJSON(new JsonResponse(message, true));
    }

    private static Person getPersonFromPersonId(String personId) {
        if (StringUtils.isEmpty(personId)) {
            throw new IllegalArgumentException("Se requiere el parametro identificador de la persona");
        }
        Person person = Person.findById(Long.parseLong(personId));
        if(person == null){
            throw new NullPointerException("No existe una persona con el identificador recivido") ;
        } return person;
    }

}
